
import { reactive } from 'vue'
import getValidator from '../static/libs/validator'
type Validator = (value: string | object, params: object) => boolean
export interface RuleProp {
  // 校验器，返回boolean
  validator: Validator;
  message: string;
}
export interface InputRef{
  error: boolean;
  value: string;
  message: string;
}
export type RulesProp = (RuleProp | string)[]
/**
 * 输入校验器
 * 校验器本身可以生成响应式数据
 * 但为了兼容有初始值的场景，特意加到参数上
 * @param rules 校验规则
 * @returns inputRef 校验结果，响应式对象 validate 触发校验器
 */
const inputValidator = (rules: RulesProp, inputRefParams?: InputRef) => {
  const inputRef = reactive(inputRefParams || {
    error: false,
    value: '',
    message: ''
  })

  const validate: ValidateFun = () => {
    console.log('触发校验')
    inputRef.error = false
    inputRef.message = ''
    for (const rule of rules) {
      let validator: Validator = () => false
      let message = ''
      if (typeof rule === 'string') {
        const validatorObj = getValidator(rule)
        if (!validatorObj) {
          return { res: false }
        }
        validator = validatorObj.validator
        message = validatorObj.message
      } else {
        validator = rule.validator
        message = rule.message
      }

      if (validator(inputRef.value, {})) {
        // 校验通过
        continue
      } else {
        // 校验失败
        inputRef.error = true
        inputRef.message = message
        return { res: false, message }
      }
    }
    return { res: true }
  }

  return { inputRef, validate }
}

export default inputValidator
